package com.jh.user.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jh.user.business.BrandManageBusiness;
import com.jh.user.business.UserBankInfoBusiness;
import com.jh.user.business.UserCoinBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.Brand;
import com.jh.user.pojo.InfoUser;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserBankInfo;
import com.jh.user.util.AliOSSUtil;
import com.jh.user.util.HttpUtils;
import com.jh.user.util.Util;

import cn.jh.common.tools.ResultWrap;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.FileUtils;
import cn.jh.common.utils.PhotoCompressUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@EnableAutoConfiguration
public class UserRealnameAuthService {
	

	private static final Logger LOG = LoggerFactory.getLogger(UserRealnameAuthService.class);

	@Value("${user.realname.uploadpath}")
	private String realnamePic;
	
	@Value("${user.realname.downloadpath}")
	private String downloadPath;
	
	@Autowired
	private UserBankInfoBusiness userBankInfoBusiness;
	
	@Autowired
	private UserLoginRegisterBusiness userLoginRegisterBusiness;
	
	@Autowired
	private UserCoinBusiness userCoinBusiness;
	
	@Autowired
	private BrandManageBusiness brandManageBusiness;
	
	@Autowired
	private UserJpushService userJpushService;
	
	@Autowired
	private AliOSSUtil aliOSSUtil;
	
	@Autowired
	Util util;
	
	/**读取用户的文件*/
	@Deprecated
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/download/realname")
	public @ResponseBody Object downloadUserPic(HttpServletRequest request,
			@RequestParam(value="brandId",required=false,defaultValue="-1")String sbrandId,
			@RequestParam(value = "phone") String phone
			){
		Map<String,Object> map = new HashMap<>();
		long brandId = -1;
		User user;
		Brand brand = null;
		try {
			brandId = Long.valueOf(sbrandId);
		} catch (NumberFormatException e) {
			brandId = -1;
		}
		if(brandId==-1){
			user =userLoginRegisterBusiness.queryUserByPhone(phone);
		}else{
			brand = brandManageBusiness.findBrandById(brandId);
			if(brand != null && "6".equals(brand.getBrandType())){
				user =userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
			}else{
				user =userLoginRegisterBusiness.queryUserByPhone(phone);
			}
		}
		
		
		
		if(user==null){
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_USER_NOT_EXISTED);
		   	map.put(CommonConstants.RESULT, null);
			map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
			return map;
			
		}
		
		brandId = user.getBrandId();
		
		/**获取身份证实名信息*/
		URI uri = util.getServiceUrl("paymentchannel", "error url request!");
		String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
		MultiValueMap<String, Long> requestEntity  = new LinkedMultiValueMap<String, Long>();
		requestEntity.add("userid", user.getId());
		
		RestTemplate restTemplate=new RestTemplate();
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================/v1.0/paymentchannel/realname/userid" + result);
		JSONObject jsonObject =  JSONObject.fromObject(result);
		JSONObject authObject  =  jsonObject.getJSONObject("realname");
		InfoUser infouser= new InfoUser();
		
		//系统编号
		infouser.setUserid(user.getId());
		
		infouser.setBrandId(user.getBrandId());
		
		infouser.setBrandName(user.getBrandname());
		//用户手机号
		infouser.setPhone(user.getPhone());
		
		//真是姓名
		infouser.setRealname(authObject.getString("realname"));
		//身份证号
		infouser.setIdcard(authObject.getString("idcard"));
		UserBankInfo ubi=new UserBankInfo();
		ubi=userBankInfoBusiness.queryDefUserBankInfoByUserid(user.getId());
		
		if(ubi!=null){
			
			//银行卡名称
			infouser.setBankName(ubi.getBankName());
			//银行卡号
			infouser.setCardNo(ubi.getCardNo());
			
		}else{
			//银行卡名称
			infouser.setBankName(null);
			//银行卡号
			infouser.setCardNo(null);
		}
		
		//用户性别
		infouser.setSex(user.getSex());
		
		//实名状态
		infouser.setRealnameStatus(user.getRealnameStatus());
		//级别
		infouser.setGrade(user.getGrade());
		//注册时间
		infouser.setCreateTime(user.getCreateTime());
		List<String> filepaths  = new ArrayList<String>();
		String src="/"+user.getBrandId()+ "/realname/"+phone;
		
		String ossObjectNamePrefix = AliOSSUtil.REAL_NAME + "-" + user.getBrandId() + "-" + phone + "-";
		String ossObjectName = "";
		
		File file = new File(realnamePic + src);
		String[] filelist = file.list();
		if (filelist != null && filelist.length > 0) {
			for (int i = 0; i < filelist.length; i++) {
				filepaths.add(downloadPath + src + "/" + filelist[i]);
			}
		}else {
			List<String> listFiles = aliOSSUtil.listFiles(ossObjectNamePrefix);
			if (listFiles != null && listFiles.size() >0) {
				for (String fileName : listFiles) {
					String fileUrl = aliOSSUtil.getFileUrl(fileName);
					filepaths.add(fileUrl);
				}
			}
		}
		
	
	   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
	   	map.put(CommonConstants.RESULT, filepaths);
	   	map.put("infouser", infouser);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}
	
	
	/**更新用户的状态*/
	@Deprecated
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/updatestatus/status")
	public @ResponseBody Object updateRealnameStatus(HttpServletRequest request,
			@RequestParam(value="brandId",required=false,defaultValue="-1")String sbrandId,
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "status") String status
			){
		
		Map<String,Object> map = new HashMap<>();
		long brandId = -1;
		User user;
		try {
			brandId = Long.valueOf(sbrandId);
		} catch (NumberFormatException e) {
			brandId = -1;
		}
		if(brandId==-1){
			user = userLoginRegisterBusiness.queryUserByPhone(phone);
		}else{
			if("6".equals(brandManageBusiness.findBrandById(brandId).getBrandType())){
				user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
			}else{
				user = userLoginRegisterBusiness.queryUserByPhone(phone);
			}
		}
		
		user.setRealnameStatus(status);
		//调用实名注册接口，将真实姓名存入用户表
//		if(status.equals("1")){
//			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
//			String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
//			MultiValueMap<String, Long> requestEntity  = new LinkedMultiValueMap<String, Long>();
//			requestEntity.add("userid", user.getId());
//			
//			RestTemplate restTemplate=new RestTemplate();
//			String result = restTemplate.postForObject(url, requestEntity, String.class);
//			JSONObject jsonObject =  JSONObject.fromObject(result);
//			JSONObject authObject  =  jsonObject.getJSONObject("realname");
//			
//			user.setFullname(authObject.getString("realname"));
//		}
		user = userLoginRegisterBusiness.saveUser(user);
		if(status.equals("1")){
			User preuser=userLoginRegisterBusiness.queryUserById(user.getPreUserId());
			if(preuser != null) {
				preuser.setEncourageNum(preuser.getEncourageNum()+1);
				userLoginRegisterBusiness.saveUser(preuser);	
			}
		}
		
		
	   	map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
	   	map.put(CommonConstants.RESULT, user);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		/**
		 * 推送信息
		 * *URL：/v1.0/user/jpush/tset
		 * **/
		String alert ="实名认证提示"; 
		String content = "亲爱的会员，实名认证已通过审核";
		//1表示审核通过  2表示审核拒绝
		if(status.equals("2")){
			content = "亲爱的会员，实名认证审核失败";
		}
		String btype="realnameStatus";
		String btypeval=status;
		
		/**获取身份证实名信息*/
//		URI uri = util.getServiceUrl("user", "error url request!");
//		String url = uri.toString() + "/v1.0/user/jpush/tset";
//		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String >();
//		requestEntity.add("userId", user.getId()+"");
//		requestEntity.add("alert", alert+"");
//		requestEntity.add("content", content+"");
//		requestEntity.add("btype",btype+"");
//		requestEntity.add("btypeval", btypeval+"");
//		RestTemplate restTemplate=new RestTemplate();
//		restTemplate.postForObject(url, requestEntity, String.class);
		userJpushService.setJpushtest(request, user.getId(), alert, content, btype, btypeval);
		return map;
	}
	

	
	/**上传 用户的照片
	 * @throws  */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/upload/realname")
	public @ResponseBody Object uploadUserPic(HttpServletRequest request,
			@RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
			@RequestParam(value = "phone") String phone) {

		Map<String, Object> map = new HashMap<>();
		long brandId = -1;
		User user;
		Brand brand = null;
		try {
			brandId = Long.valueOf(sbrandId);
		} catch (NumberFormatException e1) {
			brandId = -1;
		}
		if (brandId == -1) {
			user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果brandid=-1通过手机号查询到用户
		} else {
			brand = brandManageBusiness.findBrandById(brandId); // 如果brandid!=-1通过贴牌id找到贴牌
			if (brand != null && "6".equals(brand.getBrandType())) { // 如果贴牌类型=6
				user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId); // 通过手机号和贴牌id找到user
			} else {
				user = userLoginRegisterBusiness.queryUserByPhone(phone); // 如果贴牌类型!=6
																			// 通过手机号找到user
			}
		}
		
		if ("0".equals(user.getRealnameStatus()) || "1".equals(user.getRealnameStatus())) {
			return ResultWrap.init(CommonConstants.FALIED, "请勿重复提交实名信息!");
		}

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("image");
//		String src="/"+user.getBrandId()+ "/realname/"+phone;
		
		String ossObjectNamePrefix = AliOSSUtil.REAL_NAME + "-" + user.getBrandId() + "-" + phone + "-";
		String ossObjectName = "";
		
		/*File dir = new File(realnamePic +src );
		// 创建目录
		if (dir.mkdirs()) {
			System.out.println("创建目录" + realnamePic +src  + "成功！");

		} else {
			File[] tempfiles = dir.listFiles();
			if (tempfiles != null && tempfiles.length >0) {
				for (File file : tempfiles) {
					file.delete();
				}
			}else {
				
			}

			System.out.println("创建目录" + realnamePic +src  + "失败！");
		}*/
		List<String> listFiles = aliOSSUtil.listFiles(ossObjectNamePrefix);
		if (listFiles != null && listFiles.size() > 0) {
			for (String fileName : listFiles) {
				aliOSSUtil.deleteFileFromOss(fileName);
			}
		}

		int i = 1;
		if (files != null && files.size() > 0) {
			for (MultipartFile file : files) {

				String fileName = file.getOriginalFilename();
		    	String prefix=fileName.substring(fileName.lastIndexOf("."));
		    	fileName = System.currentTimeMillis()+i+prefix;
				ossObjectName = ossObjectNamePrefix + fileName;
				OutputStream os = new ByteArrayOutputStream();
				ByteArrayInputStream inputStream = null;
				try {
					PhotoCompressUtil.compressPhoto(file.getInputStream(), os, 0.2f);
					inputStream = FileUtils.parse(os);
					aliOSSUtil.uploadStreamToOss(ossObjectName,inputStream);
				} catch (Exception e1) {
					e1.printStackTrace();LOG.error(ExceptionUtil.errInfo(e1));
				}finally{
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
						os = null;
					}
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
						inputStream = null;
					}
				}
				
				/*File dest = new File(realnamePic +src + "/" + fileName);
		    	dest.setExecutable(true, false);
		    	dest.setReadable(true, false);
		    	dest.setWritable(true, false);
		    	dest.setWritable(true);
		    	dest.setExecutable(true);
		    	dest.setReadable(true);
				try {
					file.transferTo(dest);
					Runtime.getRuntime().exec("chmod 777 " + dest.getAbsolutePath());
				} catch (IllegalStateException e) {
					e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
				} catch (IOException e) {
					e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
				}*/
				i++;
			}
		}
		
		/*else {
			File dir = new File(realnamePic +src );
			// 创建目录
			if (dir.mkdirs()) {
				System.out.println("创建目录" + realnamePic +src  + "成功！");

			} else {

				File[] tempfiles = dir.listFiles();
				for (File file : tempfiles) {
					file.delete();
				}

				System.out.println("创建目录" + realnamePic +src  + "失败！");
			}

			if (files != null && files.size() > 0) {
				int i = 1;
				for (MultipartFile file : files) {

					String fileName = file.getOriginalFilename();
			    	String prefix=fileName.substring(fileName.lastIndexOf("."));
			    	fileName = System.currentTimeMillis()+i+prefix;
					ossObjectName = ossObjectNamePrefix + fileName;
					try {
						aliOSSUtil.uploadStreamToOss(ossObjectName,file.getInputStream());
					} catch (IOException e1) {
						e1.printStackTrace();LOG.error(ExceptionUtil.errInfo(e1));
					}

					File dest = new File(realnamePic + src + "/" + fileName);
			    	dest.setExecutable(true, false);
			    	dest.setReadable(true, false);
			    	dest.setWritable(true, false);
			    	dest.setWritable(true);
			    	dest.setExecutable(true);
			    	dest.setReadable(true);
					try {
						file.transferTo(dest);
						Runtime.getRuntime().exec("chmod 777 " + dest.getAbsolutePath());
					} catch (IllegalStateException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					} catch (IOException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
					}
					i++;
				}
			}
		}*/

//		user.setRealnameStatus("0");
//		user = userLoginRegisterBusiness.saveUser(user);

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");

		/**
		 * 推送消息 /v1.0/user/jpush/tset
		 */

		/*String alert = "实名认证提示";
		String content = "亲爱的会员，实名认证正在审核中....";
		String btype = "realnameStatus";
		String btypeval = "0";

		*//** 获取身份证实名信息 *//*
		userJpushService.setJpushtest(request, user.getId(), alert, content, btype, btypeval);*/
		if(files.size()==3){
			this.updateRealnameStatus(request, user.getBrandId()+"", user.getPhone(), "1");
		}else{
			this.updateRealnameStatus(request, user.getBrandId()+"", user.getPhone(), "2");
		}
		return map;
	}
	
	
	// 实名认证
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/upload/realname/idCard")
	public @ResponseBody Object realnameCertification(HttpServletRequest request,
			@RequestParam(value = "brandId", required = false, defaultValue = "-1") String brandIds,
			@RequestParam(value = "picNum") String picNum, @RequestParam(value = "phone") String phone,
			@RequestParam(value = "userId") long userId) {
		long brandid = Long.valueOf(brandIds);
		Map<String,Object> resultMap = new HashMap<String, Object>();
		User user;
		Brand brand = null;
		if (brandid == -1) {
			user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
		} else {
			brand = brandManageBusiness.findBrandById(brandid);
			if (brand != null && "6".equals(brand.getBrandType())) {
				user = userLoginRegisterBusiness.findUserByIdAndBrandId(userId, brandid);
			} else {
				user = userLoginRegisterBusiness.queryUserById(userId);
			}
		}
//		String src="/"+user.getBrandId()+ "/realname/"+phone;
		String ossObjectNamePrefix = AliOSSUtil.REAL_NAME + "-" + user.getBrandId() + "-" + phone + "-";
		String ossObjectName = "";
		
		// 判断用户的实名状态
		String status = userLoginRegisterBusiness.findStatusByUserId(userId);
		if (status.equals("0") || status.equals("1")) {
			resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			resultMap.put(CommonConstants.RESP_MESSAGE, "请勿重复实名");
		} else {

			if (status.equals("2") || status.equals("3")) {
				List<UserBankInfo> bankInfos = userBankInfoBusiness.queryUserBankInfoByUserid(userId);
				if (bankInfos != null) {
					userBankInfoBusiness.updateBankCardByUserId(userId);
				}
			}
			MultipartHttpServletRequest multipartRequest;
			
			List<MultipartFile> files = null;
			try {
				multipartRequest = (MultipartHttpServletRequest) request;
				files = multipartRequest.getFiles("image");
				
			} catch (Exception e1) {
				LOG.info(e1.getMessage());
			}

			/*File dir = new File(realnamePic + src );
			// 创建目录
			if (dir.mkdirs()) {
				System.out.println("创建目录" + realnamePic +src+ "成功！");

			} else {

				File[] tempfiles = dir.listFiles();
				for (File file : tempfiles) {
					// file.delete();
				}

				System.out.println("创建目录" + realnamePic + src+ "失败！");
			}*/
			
			List<String> listFiles = aliOSSUtil.listFiles(ossObjectNamePrefix);
			if (listFiles != null && listFiles.size() > 1) {
				for (String fileName : listFiles) {
					aliOSSUtil.deleteFileFromOss(fileName);
				}
			}

			if (files != null && files.size() > 0) {
				int i = 1;
				for (MultipartFile file : files) {
					String fileName = file.getOriginalFilename();
			    	String prefix=fileName.substring(fileName.lastIndexOf("."));
			    	fileName = System.currentTimeMillis()+i+prefix;
					ossObjectName = ossObjectNamePrefix + fileName;
					OutputStream os = new ByteArrayOutputStream();
					ByteArrayInputStream inputStream = null;
					try {
						PhotoCompressUtil.compressPhoto(file.getInputStream(), os, 0.2f);
						inputStream = FileUtils.parse(os);
						aliOSSUtil.uploadStreamToOss(ossObjectName,inputStream);
					} catch (Exception e1) {
						e1.printStackTrace();LOG.error(ExceptionUtil.errInfo(e1));
					}finally{
						try {
							os.close();
						} catch (IOException e) {
							e.printStackTrace();
							os = null;
						}
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
							inputStream = null;
						}
					}

					/*File dest = new File(realnamePic + src+ "/" + fileName);
			    	dest.setExecutable(true, false);
			    	dest.setReadable(true, false);
			    	dest.setWritable(true, false);
			    	dest.setWritable(true);
			    	dest.setExecutable(true);
			    	dest.setReadable(true);
					try {
						file.transferTo(dest);
						Runtime.getRuntime().exec("chmod 777 " + dest.getAbsolutePath());
					} catch (IllegalStateException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						resultMap.put(CommonConstants.RESP_MESSAGE, "参数非法异常");
						return resultMap;
					} catch (IOException e) {
						e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
						resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						resultMap.put(CommonConstants.RESP_MESSAGE, "IO异常");
						return resultMap;
					}*/
					i++;
				}
			}
			
			/**
			 * 推送消息 /v1.0/user/jpush/tset
			 */

			/*String alert = "实名认证提示";
			String content = "亲爱的会员，实名认证正在审核中....";
			String btype = "realnameStatus";
			String btypeval = "0";

			*//** 获取身份证实名信息 *//*
			userJpushService.setJpushtest(request, user.getId(), alert, content, btype, btypeval);*/
			
			String host = "https://dm-51.data.aliyun.com";
			String path = "/rest/160601/ocr/ocr_idcard.json";
			String method = "POST";
			String appcode = "a5d1104a6f73467f85a372562ea69d55";
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Authorization", "APPCODE " + appcode);
			headers.put("Content-Type", "application/json; charset=UTF-8");
			Map<String, String> querys = new HashMap<String, String>();
			boolean flag = false;

			Map<String, String> map = new HashMap<String, String>();
			if (picNum.equals("0")) {
				// 对正面图片进行base64编码
				String faceimgBase64 = "";
				try {
					MultipartFile fileFace = files.get(0);
					byte[] content = files.get(0).getBytes();

					faceimgBase64 = new String(Base64.encodeBase64(content));
				} catch (IOException e1) {
					LOG.error(e1.getMessage());
					resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					resultMap.put(CommonConstants.RESP_MESSAGE, "图片编码时出现异常");
					return resultMap;
				}

				String bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":" + "\"" + faceimgBase64 + "\""
						+ "}," + "\"configure\":{\"dataType\":50,\"dataValue\":\"{\\\"side\\\":\\\"face\\\"}\"}}]}";
				HttpResponse response;
				try {
					response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
					LOG.info("=====================身份证正面验证状态====================="+ response.getStatusLine().getStatusCode());
					if (response.getStatusLine().getStatusCode() == 200) {
						System.out.println(response.toString());
						String str = EntityUtils.toString(response.getEntity());
						JSONObject jsonObject = JSONObject.fromObject(str);
						String resultobj = jsonObject.getString("outputs");
						JSONArray jsonArray = JSONArray.fromObject(resultobj);

						String output = jsonArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
						JSONObject out = JSONObject.fromObject(output);
						String address = out.getString("address");
						String realname = out.getString("name");
						String idCard = out.getString("num");
						String birth = out.getString("birth");
						map.put("address", address);
						map.put("name", realname);
						map.put("idCard", idCard);
						map.put("birth", birth);
						String birthDate =  birth.substring(0,4);
						int birthYear = Integer.valueOf(birthDate);
						int nowYear = Integer.valueOf(DateUtil.getDateStringConvert(new String(), new Date(), "yyyy"));
						if (nowYear - birthYear < 18 || nowYear - birthYear > 80) {
							resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							resultMap.put(CommonConstants.RESP_MESSAGE, "很抱歉,仅对年龄18岁~80岁用户进行实名认证!");
							return resultMap;
						} else {
							URI uri = util.getServiceUrl("paymentchannel", "error url request!");
							String url = uri.toString() + "/v1.0/paymentchannel/realname/auth/backstage";
							/** 根据的用户userid查询用户的基本信息 */
							MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("userid", userId + "");
							requestEntity.add("realname", realname);
							requestEntity.add("idcard", idCard);
							RestTemplate restTemplate = new RestTemplate();
							String result = restTemplate.postForObject(url, requestEntity, String.class);
							JSONObject fs = JSONObject.fromObject(result);
							System.out.println(fs.getString("resp_code"));
							String msgResult = fs.getJSONObject("result").getString("result");
							if (fs.getString("resp_code").equals("000000") && msgResult.equals("1")) {
								resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
								resultMap.put("faceMsg", map);
								resultMap.put(CommonConstants.RESP_MESSAGE, "成功");
								flag = true;
							} else {
								resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
								resultMap.put(CommonConstants.RESP_MESSAGE, "审核失败");
								LOG.info("=====================身份证正面审核错误" + response.getStatusLine().getStatusCode()
										+ "========================");
								return resultMap;
							}
						}
					}
				} catch (Exception e) {
					LOG.info(e.getMessage());
					resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					resultMap.put(CommonConstants.RESP_MESSAGE, "身份证正面审核出现异常");
					return resultMap;
				}

			}

			if (picNum.equals("1")) {
				// 对反面图片进行base64编码
				String backimgBase64 = "";
				try {
					byte[] content = files.get(0).getBytes();
					backimgBase64 = new String(Base64.encodeBase64(content));
					String bodys2 = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":" + "\"" + backimgBase64
							+ "\"" + "},"
							+ "\"configure\":{\"dataType\":50,\"dataValue\":\"{\\\"side\\\":\\\"back\\\"}\"}}]}";
					HttpResponse responseBk = HttpUtils.doPost(host, path, method, headers, querys, bodys2);
					LOG.info("=====================身份证反面验证状态====================="
							+ responseBk.getStatusLine().getStatusCode());
					JSONObject backJson = null;
					if (responseBk.getStatusLine().getStatusCode() == 200) {
						flag = true;
						String str = EntityUtils.toString(responseBk.getEntity());
						JSONObject jsonObject = JSONObject.fromObject(str);
						String resultobj = jsonObject.getString("outputs");
						JSONArray jsonArray = JSONArray.fromObject(resultobj);

						String output = jsonArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue"); // 取出结果json字符串
						JSONObject out = JSONObject.fromObject(output);
						String startDate = out.getString("start_date");
						String endDate = out.getString("end_date");
						String issue = out.getString("issue");
						map.put("startDate", startDate);
						map.put("endDate", endDate);
						map.put("issue", issue);
						// 修改用户实名状态
						userLoginRegisterBusiness.updateUserStatusByUserId(userId);
						resultMap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						resultMap.put("backMsg", map);
						resultMap.put(CommonConstants.RESP_MESSAGE, "成功");
						flag = true;

					} else {
						resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						resultMap.put(CommonConstants.RESP_MESSAGE, "审核失败");
						LOG.info("=====================身份证正面审核错误" + responseBk.getStatusLine().getStatusCode()
								+ "========================");
					}
				} catch (IOException e1) {
					LOG.error(e1.getMessage());
					resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					resultMap.put(CommonConstants.RESP_MESSAGE, "身份证背面审核出现异常");
					return resultMap;
				} catch (Exception e) {
					LOG.error(e.getMessage());
					resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					resultMap.put(CommonConstants.RESP_MESSAGE, "身份证背面审核出现异常");
					return resultMap;
				}
			}
			// 将图片保存在服务器中
			/*if (flag) {
				if (files != null && files.size() > 0) {
					for (MultipartFile file : files) {
						String photoName = null;
						String fileName = file.getOriginalFilename();
						int index  = fileName.lastIndexOf(".");
						String lastName = fileName.substring(index, fileName.length());
					    if(picNum.equals("0")){
					    	 photoName = "face"+lastName;
					    }else{
					       	 photoName = "back"+lastName;
					    }
					    
						File dest = new File(realnamePic + src  + "/" + photoName);
				    	dest.setExecutable(true, false);
				    	dest.setReadable(true, false);
				    	dest.setWritable(true, false);
				    	dest.setWritable(true);
				    	dest.setExecutable(true);
				    	dest.setReadable(true);
				    	if(dest.exists()) {
							dest.delete();
						}
						try {
							file.transferTo(dest);
							Runtime.getRuntime().exec("chmod 777 " + dest.getAbsolutePath());
						} catch (IllegalStateException e) {
							e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
							resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							resultMap.put(CommonConstants.RESP_MESSAGE, "保存图片时参数异常");
							return resultMap;
						} catch (IOException e) {
							e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
							resultMap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
							resultMap.put(CommonConstants.RESP_MESSAGE, "上传照片发生异常");
							return resultMap;
						}
					}
				}
			}*/
			if ("1".equals(picNum)) {
				if(listFiles.size()>= 1){
					this.updateRealnameStatus(request, user.getBrandId()+"", user.getPhone(), "1");
				}else{
					this.updateRealnameStatus(request, user.getBrandId()+"", user.getPhone(), "2");
				}
			}
		}
		return resultMap;
	}

	//根据brandid和status获取一定时间段内的信息
	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/query/querynamebystatus")
	public Object queryFullNameByStatus(HttpServletRequest request,
			@RequestParam(value = "brand_id",defaultValue="0",required=false) long brandId,
			@RequestParam(value = "realnameStatus",defaultValue="0,1,2,3",required=false) ArrayList<String> status,
			@RequestParam(value = "start_time",required=false) String startTime,
			@RequestParam(value = "end_time",required=false) String endTime) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			
			Date startTimeDate = null;
			if (startTime != null && !startTime.equalsIgnoreCase("")) {
				try {
					startTimeDate = DateUtil.getDateFromStr(startTime);
				} catch (Exception e) {
					startTimeDate = DateUtil.getDateFromStr("2017-05-01");
				}
			} else {
				startTimeDate = DateUtil.getDateFromStr("2017-05-01");
			}
			Date endTimeDate = null;
			if (endTime != null && !endTime.equalsIgnoreCase("")) {
				endTimeDate = DateUtil.getDateFromStr(endTime);
			} else {
				endTimeDate = new Date();
			}
			
			int number = 0;
			if (brandId == 0) {
				number = userCoinBusiness.findFullNameByStatus(status, startTimeDate, endTimeDate);
			}else {
				number = userCoinBusiness.findFullNameByStatus(brandId, status, startTimeDate, endTimeDate);
			}
			
			if (number == 0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "查询成功，无相关数据");
				map.put(CommonConstants.RESULT, 0);
			}else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "查询成功");
				map.put(CommonConstants.RESULT, number);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败");
		}
		return map;
	}
	
}
